//
//  NotificationsViewController.m
//  UADE-Mobile
//
//  Created by Nico on 11/06/12.
//  Copyright (c) 2012 DG. All rights reserved.
//

#import "NotificationsViewController.h"
#import "NotificationsHelper.h"
#import "TTNotificationsDataSource.h"
#import "TTTableFileItem.h"
#import "AppDelegate.h"

@interface NotificationsViewController ()

@end

@implementation NotificationsViewController

NSMutableArray* notifications;
NSMutableArray* coursesForNotifications;

- (id)initWithStyle:(UITableViewStyle)style
{
    self = [super initWithStyle:style];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void) createModel { 
    coursesForNotifications = [[NSMutableArray alloc]init ];
    
    self.title = NSLocalizedString(@"Notifications", @"");
    self.tableView.rowHeight = 70.0f;
    
    NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
    notifications = (NSMutableArray*)[prefs objectForKey:@"notifications"];

    if (notifications == nil){
        notifications = [[NSMutableArray alloc]init];
    }

    NSMutableArray * items = [NSMutableArray array];

    for(NSDictionary * eachNotification in notifications ){
        
        NSString* materia;
        NSString* mensajesNotificacion;
        NSNumber* tipoNotificacion;
        
        StudentModel* model = [StudentModel SharedInstance];
        NSArray* records = [model records];
        NSDictionary* course;
        for (NSDictionary* item in records) {
            NSArray* clases = [item objectForKey:@"Clases"];
            for(NSDictionary* clase in clases){
                NSNumber* idAula = [clase objectForKey:@"IDAula"];
                if ([idAula intValue] == [[eachNotification objectForKey:@"IdAula"] intValue]) {
                    course = clase;
                }
            }
        }   
        
        
        if (course != nil) {
            tipoNotificacion = [eachNotification objectForKey:@"TipoNotificacion"];
            switch ([tipoNotificacion intValue]) {
                case 1:
                {
                    mensajesNotificacion = @"Nueva noticia";                    
                    break;
                }
                case 2:
                {
                    mensajesNotificacion = @"Nueva nota";
                    break;
                }
                case 3:
                {
                    mensajesNotificacion = @"Nuevo archivo";
                    break;
                }
                case 4:
                {
                    mensajesNotificacion = @"Nuevo mensaje de grupo";
                    break;
                }
                case 5:
                {
                    mensajesNotificacion = @"Nuevo archivo de grupo";
                    break;
                }   
                default:
                    break;
            }
            materia = [course objectForKey:@"NombreMateria"];
            [coursesForNotifications addObject:course];
        }
        else {
            [coursesForNotifications addObject:[NSNull null]];
        }
        
        //NSLog(@"materia: %@", materia);
        //NSLog(@"mensajesNotificacion %@", mensajesNotificacion);
        if (materia != nil && mensajesNotificacion != nil) {
            TTTableItem *tableItem = 
            [TTTableSubtitleItem 
             itemWithText:materia
             subtitle:[NSString stringWithFormat:@"%@", 
                       mensajesNotificacion]
             URL:nil];
            
            [items addObject:tableItem];
        }
        
    }
    
    self.dataSource = [TTNotificationsDataSource dataSourceWithItems:items];
    AppDelegate* appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    [appDelegate performSelectorOnMainThread:@selector(hideProgressHUD) withObject:nil waitUntilDone:YES];
} 


- (void)viewDidLoad
{
    [super viewDidLoad];
    
    // Uncomment the following line to preserve selection between presentations.
    // self.clearsSelectionOnViewWillAppear = NO;
 
    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem;
}


- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}


/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
    }   
    else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath
{
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
 
*/


- (void)didSelectObject:(id)object atIndexPath:(NSIndexPath*)indexPath{
    NSMutableArray* notificationsMutable = [notifications mutableCopy];

    NSDictionary* touched = [notificationsMutable objectAtIndex:indexPath.row];
    NSDictionary* course = [coursesForNotifications objectAtIndex:indexPath.row];
    if ([course isKindOfClass:[NSNull class]]) {
        return;
    }
    [notificationsMutable removeObjectAtIndex:indexPath.row];
    [coursesForNotifications removeObjectAtIndex:indexPath.row];
    NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
    
    [prefs setObject:notificationsMutable  forKey:@"notifications"];
    [prefs synchronize];
    [self invalidateModel];

    NSNumber* tipoNotificacion;
    NSString* url;
    tipoNotificacion = [touched objectForKey:@"TipoNotificacion"];

    switch ([tipoNotificacion intValue]) {
        case 1:
        {
            url =  [NSString stringWithFormat:@"tt://news/%@",[course objectForKey:@"IDAula"]];
            [[TTNavigator navigator] openURLAction:[[[TTURLAction actionWithURLPath:url] applyQuery:course] applyAnimated:TRUE]];            
            break;
        }
        case 2:
        {
            [[TTNavigator navigator] openURLAction:[[[TTURLAction actionWithURLPath:@"tt://detail"] applyQuery:course] applyAnimated:TRUE]];
            break;
        }
        case 3:
        {
            url =  [NSString stringWithFormat:@"tt://download/%@",[course objectForKey:@"IDAula"]];

            [[TTNavigator navigator] openURLAction:[[TTURLAction actionWithURLPath:url] applyAnimated:FALSE]];
            break;
        }
        case 4:
        case 5:
        {
            url =  [NSString stringWithFormat:@"tt://foro/%@",[course objectForKey:@"IDAula"]];

            [[TTNavigator navigator] openURLAction:[[TTURLAction actionWithURLPath:url] applyAnimated:FALSE]];
            break;
        }   
        default:
            break;
    }
}

@end
